package cn.practice.weibopractice.common.exception;

import cn.practice.weibopractice.common.response.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice

public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult handleConstraintViolationException(ConstraintViolationException ex) {
        log.error("系统异常", ex.getMessage());
        return JsonResult.fail(ex.getMessage());
    }

    @ExceptionHandler
    public JsonResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.error("系统异常", ex.getFieldError().getDefaultMessage());
        return JsonResult.fail(ex.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult handleThrowable(Throwable ex) {
        log.error("系统异常", ex.getMessage());
        return JsonResult.exception(ex.getMessage());
    }
}
